package com.shengdong.water.code.viewmodel

import androidx.databinding.ObservableField
import com.shengdong.water.base.BaseViewModel
import com.shengdong.water.code.bean.UserToken
import com.shengdong.water.code.utils.SM4Util
import com.shengdong.water.code.repository.ApiRepository
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import javax.inject.Inject

@HiltViewModel
class LoginViewModel @Inject constructor(
    private val repository: ApiRepository
) : BaseViewModel() {
    
    val account = ObservableField("")
    val password = ObservableField("")

    private val _userToken = MutableStateFlow<UserToken?>(null)
    val userToken : StateFlow<UserToken?> = _userToken
    
    
    fun login() {
        val accountValue = account.get()?: ""
        val passwordValue = password.get()?: ""
        handleRequest(
            loading = "登录中...",
            flow = repository.login(accountValue, SM4Util.encryptDataCBC(passwordValue)!!),
            onSuccess = { _userToken.value = it},
            onError = { code ,msg ->
                when (code) {
                    401 ->  {}// 处理未授权
                    403 -> {}// 处理禁止访问
                    else -> showError("获取用户信息失败: [$code] $msg")
                }

            },
            onToast =  {
                it
            },
            onException = {e ->
                showError("发生错误: ${e.message}")
            },
        )
    }
}